package org.linlinjava.litemall.db.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.linlinjava.litemall.db.dao.AgedmallLeaseGoodsReturnRecordMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallShopMapper;
import org.linlinjava.litemall.db.domain.AgedmallLeaseGoodsReturnRecord;
import org.linlinjava.litemall.db.domain.AgedmallLeaseGoodsReturnRecordExample;
import org.linlinjava.litemall.db.vo.anno.OrderContentDto;
import org.linlinjava.litemall.db.vo.anno.OrderContentGoodsDto;
import org.linlinjava.litemall.db.vo.logistics.*;
import org.linlinjava.litemall.db.vo.wechat.ApplicationCardMessage;
import org.linlinjava.litemall.db.vo.wechat.GoodsMessage;
import org.linlinjava.litemall.db.vo.wechat.SeparateWechatData;
import org.linlinjava.litemall.db.vo.wechat.TextCardDescMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wj
 * @date 2021/11/3 13:44
 */
@Component
public class LogisticsGoodsUtil {


    @Resource
    private AgedmallShopMapper agedmallShopMapper;

    @Resource
    private AgedmallLeaseGoodsReturnRecordMapper agedmallLeaseGoodsReturnRecordMapper;


    /**
     * 组装数据
     * @return
     */
    public LogisticsCommonData assemblyData(List<Integer> orderGoodsIdList,LogisticsBackUserAddressData backUserAddress){
        LogisticsCommonData commonData=new LogisticsCommonData();
        if(orderGoodsIdList.isEmpty()){
            return null;
        }
        SeparateWechatData storeMessageByOrderGoodsId = agedmallShopMapper.getStoreMessageByOrderGoodsId(orderGoodsIdList.get(0));

        LogisticsTimeData timeData=assemblyTimeData(storeMessageByOrderGoodsId.getDeliverySn(),
                storeMessageByOrderGoodsId.getDeliveryChoose(),storeMessageByOrderGoodsId.getAddTime()
                ,storeMessageByOrderGoodsId.getOrderId());

        LogisticsStoreCloudData storeCloudData=new LogisticsStoreCloudData(storeMessageByOrderGoodsId);

        LogisticsUserData userData=new LogisticsUserData(storeMessageByOrderGoodsId);

        List<LogisticsGoodsData> goodsDataList = assemblyGoodsData(orderGoodsIdList);

        LogisticsOrderData orderData=new LogisticsOrderData(storeMessageByOrderGoodsId);
        commonData.setTimeData(timeData);
        commonData.setStoreCloudData(storeCloudData);
        commonData.setUserData(userData);
        commonData.setGoodsDataList(goodsDataList);
        commonData.setOrderData(orderData);
        if (null!=backUserAddress){
            commonData.setBackUserAddress(backUserAddress);
        }
        return commonData;

    }

    public static String getGoodsDeliveryTime(String deliverySn,String deliveryChoose, LocalDateTime time){
        String backTime=null;
        //加急
        if(deliverySn.equals(AgedmallShipDictConstant.SHIP_SN_URGENT)){
            JSONObject jsonObject=JSON.parseObject(deliveryChoose);
            Integer earlyHour=(Integer) jsonObject.get("earlyUrgentPay");
            Integer laterHour=(Integer)jsonObject.get("lastUrgentPay");
            Integer lastHour=laterHour+earlyHour;
            Date addTime=Date.from( time.
                    atZone( ZoneId.systemDefault()).toInstant());
            DateTime earlyDay = DateUtil.offsetHour(addTime,earlyHour);
            DateTime lastDay = DateUtil.offsetHour(addTime,lastHour);
            String earlyFormat = DateUtil.format(earlyDay, "yyyy-MM-dd HH:mm");
            String lastFormat = DateUtil.format(lastDay, "HH:mm");
            backTime=earlyFormat+"-"+lastFormat;
            return backTime;
        }
        //预约
        else if (deliverySn.equals(AgedmallShipDictConstant.SHIP_SN_SUBSCRIBE)){
            JSONObject jsonObject=JSON.parseObject(deliveryChoose);
            String date=(String) jsonObject.get("date");
            String startTime=(String)jsonObject.get("startTime");
            String endTime=(String)jsonObject.get("entTime");
            backTime=date+" "+startTime+"-"+endTime;
            return backTime;
        }
//        dayHourReach 今日小时达（今日送货到医院）=（普通配送费+加急费）
//        subHourReach 预约小时达（预约送货到医院）=（普通配送费+预约费）
//        dayStoreSelf 今日门店自提 =（普通配送费+自提费）
//        subStoreSelf 预约门店自提 =（普通配送费+预约费）
//        subHospitalSelf 预约到院自提（预约到桩自提）=（普通配送费+预约费）
        else if (deliverySn.equals(AgedmallShipDictConstant.SHIP_SN_HOSPITAL)){
            JSONObject jsonObject=JSON.parseObject(deliveryChoose);
            String date=(String) jsonObject.get("date");
            String startTime=(String)jsonObject.get("startTime");
            String endTime=(String)jsonObject.get("endTime");
            backTime=date+" "+startTime+"-"+endTime;
            return backTime;
        }
        return backTime;
    }

    public LogisticsTimeData assemblyTimeData(String deliverySn, String deliveryChoose, LocalDateTime time,Integer orderId){
        LogisticsTimeData timeData=new LogisticsTimeData();
        //加急
        if((deliverySn.equals(AgedmallShipDictConstant.SHIP_SN_URGENT))){
            timeData.setUrgentTime(getGoodsDeliveryTime(deliverySn,deliveryChoose,time));
        }

        //预约
        if((deliverySn.equals(AgedmallShipDictConstant.SHIP_SN_SUBSCRIBE))) {
            timeData.setSubscribeTime(getGoodsDeliveryTime(deliverySn, deliveryChoose, time));
        }
        //医院小时达
            if((deliverySn.equals(AgedmallShipDictConstant.SHIP_SN_HOSPITAL))){
                JSONObject jsonObject=JSON.parseObject(deliveryChoose);
                String type=(String) jsonObject.get("type");
                if(type.equals("subHourReach")||type.equals("subStoreSelf")||type.equals("subHospitalSelf")){
                    timeData.setHospitalHourSubTime(getGoodsDeliveryTime(deliverySn,deliveryChoose,time));
                }
                else if(type.equals("dayHourReach")){
                    timeData.setHospitalHourTime(getGoodsDeliveryTime(deliverySn,deliveryChoose,time));
                }
            }

        AgedmallLeaseGoodsReturnRecordExample recordExample=new AgedmallLeaseGoodsReturnRecordExample();
        recordExample.or().andSubOrderIdsEqualTo(orderId.toString()).andGetGoodsStyleEqualTo((byte)0);
        AgedmallLeaseGoodsReturnRecord agedmallLeaseGoodsReturnRecord = agedmallLeaseGoodsReturnRecordMapper.selectOneByExample(recordExample);
        if(ObjectUtil.isNotNull(agedmallLeaseGoodsReturnRecord)){
            LocalDateTime date=agedmallLeaseGoodsReturnRecord.getDate();
            String dateFormat=DateUtil.format(date,"yyyy-MM-dd");
            timeData.setPickUpTime(dateFormat+" "+agedmallLeaseGoodsReturnRecord.getTime()+"前");
        }
        return timeData;
    }

    public List<LogisticsGoodsData> assemblyGoodsData(List<Integer> orderGoodsIds){
        List<LogisticsGoodsData> goodsDataList=new ArrayList<>();
        List<SeparateWechatData> separateWechatDataList = agedmallShopMapper.getStoreMessageByOrderGoodsList(orderGoodsIds);
        for (int i = 0; i < separateWechatDataList.size(); i++) {
            SeparateWechatData separateWechatData=separateWechatDataList.get(i);
            LogisticsGoodsData goodsData=new LogisticsGoodsData();
            goodsData.setOrderGoodsId(separateWechatData.getOrderGoodsId());
            goodsData.setGoodsName(separateWechatData.getGoodsName());
            goodsData.setGoodsAmount(separateWechatData.getPrice());
            goodsData.setGoodsCount(separateWechatData.getNumber().toString());
            goodsData.setDeposit(separateWechatData.getGoodsType().equals("lease"));
            goodsData.setRfid(separateWechatData.getRfid());
            goodsData.setOrderGoodsId(separateWechatData.getOrderGoodsId());
            goodsData.setPicUrl(separateWechatData.getPicUrl());
            JSONArray jsonArray=JSON.parseArray(separateWechatData.getSpecifications());
            StringBuffer specString=new StringBuffer();
            jsonArray.forEach( json->{
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(json));
                String specName=(String) jsonObject.get("name");
                specString.append(specName).append(" ");
            });

            goodsData.setSpec(specString.toString());

            if((separateWechatData.getDeliverySn().equals(AgedmallShipDictConstant.SHIP_SN_URGENT))){
                goodsData.setUrgentTime(getGoodsDeliveryTime(separateWechatData.getDeliverySn(),separateWechatData.getDeliveryChoose()
                        ,separateWechatData.getAddTime()));
            }

            //预约
            if((separateWechatData.getDeliverySn().equals(AgedmallShipDictConstant.SHIP_SN_SUBSCRIBE))) {
                goodsData.setSubscribeTime(getGoodsDeliveryTime(separateWechatData.getDeliverySn(),separateWechatData.getDeliveryChoose()
                        ,separateWechatData.getAddTime()));
            }
            //医院小时达
            if((separateWechatData.getDeliverySn().equals(AgedmallShipDictConstant.SHIP_SN_HOSPITAL))){
                JSONObject jsonObject=JSON.parseObject(separateWechatData.getDeliveryChoose());
                String type=(String) jsonObject.get("type");
                if(type.equals("subHourReach")||type.equals("subStoreSelf")||type.equals("subHospitalSelf")){
                    goodsData.setHospitalHourSubTime(getGoodsDeliveryTime(separateWechatData.getDeliverySn(),separateWechatData.getDeliveryChoose()
                            ,separateWechatData.getAddTime()));
                }
                else{
                    goodsData.setHospitalHourTime(getGoodsDeliveryTime(separateWechatData.getDeliverySn(),separateWechatData.getDeliveryChoose()
                            ,separateWechatData.getAddTime()));
                }
            }
            goodsDataList.add(goodsData);
        }
        return goodsDataList;
    }


    /**
     *  json转实体类
     * @return
     */
    public static LogisticsCommonData parseObject(String json){
      return  JSON.parseObject(json,LogisticsCommonData.class);
    }

    /**
     * 获取保存的common数据字符串
     * @return
     */
    public String toJsonStringByOrderGoodsId(List<Integer> orderGoodsIdList,LogisticsBackUserAddressData backUserAddress){
        return JSONObject.toJSONString(assemblyData(orderGoodsIdList,backUserAddress));
    }


    /**
     * 数据 ----> 企业微信按钮模板
     * @return
     */
    public static ApplicationCardMessage commonDataToApplicationCard(LogisticsCommonData logisticsCommonData,Integer type){
        ApplicationCardMessage applicationCardMessage=new ApplicationCardMessage();
        LogisticsTimeData timeData = logisticsCommonData.getTimeData();
        if(ObjectUtil.isNotNull(timeData)){
            applicationCardMessage.setUrgentTime(timeData.getUrgentTime());
            applicationCardMessage.setSubscribeTime(timeData.getSubscribeTime());
            applicationCardMessage.setPickUpTime(timeData.getPickUpTime());
            applicationCardMessage.setHospitalHourTime(timeData.getHospitalHourTime());
            applicationCardMessage.setHospitalHourSubTime(timeData.getHospitalHourSubTime());
        }
        List<LogisticsGoodsData> goodsDataList = logisticsCommonData.getGoodsDataList();
        if(!goodsDataList.isEmpty()){
            List<GoodsMessage> goodsMessageList=new ArrayList<>();
            goodsDataList.forEach( goodsData ->goodsMessageList.add(new GoodsMessage(goodsData)));
            applicationCardMessage.setGoodsMessageList(goodsMessageList);
        }
        applicationCardMessage.setOrderSn(logisticsCommonData.getOrderData().getBigOrderSn());

        //        0-配货 1-送货 2-取货 3-维护
        LogisticsStoreCloudData storeCloudData=logisticsCommonData.getStoreCloudData();
        LogisticsUserData userData=logisticsCommonData.getUserData();
        if(type==0){
            applicationCardMessage.setStoreName(storeCloudData.getName());
            applicationCardMessage.setStoreAddress(storeCloudData.getAddress());
        }
        else if(type==1){

            applicationCardMessage.setStoreName(storeCloudData.getName());
            applicationCardMessage.setStoreAddress(storeCloudData.getAddress());
            applicationCardMessage.setSendUserName(userData.getName());
            applicationCardMessage.setSendUserPhone(userData.getPhone());
            applicationCardMessage.setSendAddress(userData.getAddress());
        }
        else if(type==2){
            applicationCardMessage.setPickUpAddress(userData.getAddress());
            applicationCardMessage.setPickUpUserName(userData.getName());
            applicationCardMessage.setPickUpUserPhone(userData.getPhone());
            applicationCardMessage.setClosedStoreName(storeCloudData.getName());
            applicationCardMessage.setClosedStoreAddress(storeCloudData.getAddress());
        }
        else if(type==3){
            applicationCardMessage.setMaintainStoreName(storeCloudData.getName());
            applicationCardMessage.setMaintainStoreAddress(storeCloudData.getAddress());
        }
    return applicationCardMessage;
    }

    /**
     * 数据 ----> 企业微信群聊卡片模板
     * @return
     */
    public static TextCardDescMessage commonDataToTextCardDesc(LogisticsCommonData logisticsCommonData,Integer type){
        TextCardDescMessage textCardDescMessage=new TextCardDescMessage();
        textCardDescMessage.setType(type);
        LogisticsTimeData timeData = logisticsCommonData.getTimeData();
        if(ObjectUtil.isNotNull(timeData)){
            textCardDescMessage.setUrgentTime(timeData.getUrgentTime());
            textCardDescMessage.setSubscribeTime(timeData.getSubscribeTime());
            textCardDescMessage.setPickUpTime(timeData.getPickUpTime());
            textCardDescMessage.setHospitalHourTime(timeData.getHospitalHourTime());
            textCardDescMessage.setHospitalHourSubTime(timeData.getHospitalHourSubTime());
        }
        List<LogisticsGoodsData> goodsDataList = logisticsCommonData.getGoodsDataList();
        if(!goodsDataList.isEmpty()){
            textCardDescMessage.setGoodsName(goodsDataList.get(0).getGoodsName());
        }
        //        0-配货 1-送货 2-取货 3-维护
        LogisticsStoreCloudData storeCloudData=logisticsCommonData.getStoreCloudData();
        LogisticsUserData userData=logisticsCommonData.getUserData();
        if(type==0){
            textCardDescMessage.setStoreName(storeCloudData.getName());
            textCardDescMessage.setAddress(storeCloudData.getAddress());
        }
        else if(type==1){

            textCardDescMessage.setPickUpAddress(storeCloudData.getAddress());
            textCardDescMessage.setDeliveryAddress(userData.getAddress());

        }
        else if(type==2){
            textCardDescMessage.setPickUpAddress(userData.getAddress());
            textCardDescMessage.setDeliveryAddress(storeCloudData.getAddress());
        }
        else if(type==3){
            textCardDescMessage.setMaintainAddress(storeCloudData.getAddress());
        }
        return textCardDescMessage;
    }



    /**
     * 数据 ----> 订单播报机凭条
     * @return
     */
    public static OrderContentDto commonDataToOrderAnno(LogisticsCommonData logisticsCommonData){
        OrderContentDto orderContentDto=new OrderContentDto();
        LogisticsStoreCloudData storeCloudData = logisticsCommonData.getStoreCloudData();
        LogisticsOrderData orderData = logisticsCommonData.getOrderData();
        LogisticsUserData userData = logisticsCommonData.getUserData();
        orderContentDto.setLogisticsName(storeCloudData.getLogisticsName());
        orderContentDto.setLogisticsPhone(storeCloudData.getLogisticsPhone());
        orderContentDto.setIsThirdPart(storeCloudData.getIsThirdPart());

        List<OrderContentGoodsDto> goodsList =new ArrayList<>();
        List<LogisticsGoodsData> goodsDataList = logisticsCommonData.getGoodsDataList();
        goodsDataList.forEach(goodsData -> {
            goodsList.add(new OrderContentGoodsDto(goodsData));
        });
        orderContentDto.setGoodsList(goodsList);
        orderContentDto.setStoreName(storeCloudData.getName());
        orderContentDto.setStorePhone(storeCloudData.getStorePhone());
        orderContentDto.setOrderSn(orderData.getBigOrderSn());
        orderContentDto.setPayNo(orderData.getPayId());
        orderContentDto.setUserName(userData.getName());
        orderContentDto.setUserPhone(userData.getPhone());
        orderContentDto.setUserAddress(userData.getAddress());
        return orderContentDto;
    }


}
